<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信公众号文章自动生成工具</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { background: #2c3e50; color: white; padding: 20px; text-align: center; }
        .nav { display: flex; background: #34495e; }
        .nav-item { flex: 1; padding: 15px; text-align: center; cursor: pointer; color: white; border: none; background: none; }
        .nav-item.active { background: #3498db; }
        .content { padding: 20px; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .card { background: #f8f9fa; padding: 20px; margin: 10px 0; border-radius: 8px; border: 1px solid #dee2e6; }
        .btn { padding: 10px 20px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; }
        .btn-primary { background: #007bff; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-info { background: #17a2b8; color: white; }
        .btn-error { background: #dc3545; color: white; }
        .form-control { width: 100%; padding: 10px; margin: 5px 0; border: 1px solid #ddd; border-radius: 4px; }
        .form-group { margin: 10px 0; }
        .alert { padding: 15px; margin: 10px 0; border-radius: 5px; }
        .alert-success { background: #d4edda; color: #155724; }
        .alert-error { background: #f8d7da; color: #721c24; }
        .alert-info { background: #d1ecf1; color: #0c5460; }
        
        /* 进度提示样式 */
        .progress-alert {
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            border: none;
        }
        
        .progress-text {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .progress-bar-container {
            width: 100%;
            height: 8px;
            background: rgba(255,255,255,0.2);
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #00d2ff 0%, #3a7bd5 100%);
            border-radius: 4px;
            transition: width 0.8s ease-in-out;
            box-shadow: 0 2px 10px rgba(0,210,255,0.3);
        }
        
        .progress-percentage {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
            opacity: 0.9;
        }
        .loading { text-align: center; padding: 20px; }
        .status-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0; }
        .status-item { text-align: center; padding: 20px; background: #e9ecef; border-radius: 8px; }
        .status-value { font-size: 2em; font-weight: bold; color: #007bff; }
        
        /* 文章预览样式 */
        .article-preview-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .article-preview-content {
            background-color: #fefefe;
            margin: 2% auto;
            padding: 0;
            border-radius: 10px;
            width: 90%;
            max-width: 800px;
            max-height: 90%;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }
        
        .article-preview-header {
            background: #2c3e50;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .article-preview-title {
            margin: 0;
            font-size: 1.2em;
        }
        
        .article-preview-controls {
            display: flex;
            gap: 10px;
        }
        
        .article-preview-body {
            padding: 20px;
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .article-meta {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #007bff;
        }
        
        .article-content {
            line-height: 1.8;
            font-size: 16px;
            color: #333;
        }
        
        /* 微信富文本样式 */
        .wechat-format {
            font-family: 'Microsoft YaHei', sans-serif;
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }
        
        .wechat-format h1, .wechat-format h2, .wechat-format h3 {
            color: #333;
            margin: 20px 0 15px 0;
        }
        
        .wechat-format p {
            margin: 15px 0;
            text-align: justify;
        }
        
        .wechat-format img {
            max-width: 100%;
            height: auto;
            margin: 15px 0;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .wechat-format ul {
            padding-left: 20px;
        }
        
        .wechat-format li {
            margin: 8px 0;
        }
        
        /* 原始内容样式 */
        .raw-content {
            font-family: 'Courier New', monospace;
            background: #f8f8f8;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #ddd;
            white-space: pre-wrap;
            font-size: 14px;
            color: #555;
        }
        
        .close-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .close-btn:hover {
            background: #c82333;
        }
        
        .format-toggle {
            background: #17a2b8;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .format-toggle:hover {
            background: #138496;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 微信公众号文章自动生成工具</h1>
            <p>基于AI的智能内容创作助手</p>
        </div>
        
        <div class="nav">
            <button class="nav-item active" onclick="switchTab('dashboard')">📊 仪表板</button>
            <button class="nav-item" onclick="switchTab('themes')">📋 主题管理</button>
            <button class="nav-item" onclick="switchTab('articles')">📝 文章生成</button>
            <button class="nav-item" onclick="switchTab('settings')">⚙️ 系统设置</button>
        </div>
        
        <div class="content">
            <!-- 仪表板 -->
            <div id="dashboard" class="tab-content active">
                <div id="status-display" class="status-grid">
                    <div class="status-item">
                        <div class="status-value" id="theme-count">-</div>
                        <div>主题数量</div>
                    </div>
                    <div class="status-item">
                        <div class="status-value" id="article-count">-</div>
                        <div>生成文章</div>
                    </div>
                    <div class="status-item">
                        <div class="status-value">运行中</div>
                        <div>系统状态</div>
                    </div>
                </div>
                
                <div class="card">
                    <h3>📖 快速开始</h3>
                    <p>1. 在"主题管理"中创建内容主题</p>
                    <p>2. 在"文章生成"中选择主题生成文章</p>
                    <p>3. 生成的文章可以发布到微信公众号</p>
                    <button class="btn btn-primary" onclick="switchTab('themes')">开始创建主题</button>
                    <a href="/docs" target="_blank" class="btn btn-info">📚 API文档</a>
                </div>
            </div>
            
            <!-- 主题管理 -->
            <div id="themes" class="tab-content">
                <div class="card">
                    <h3>📋 创建新主题</h3>
                    <form id="theme-form">
                        <div class="form-group">
                            <input type="text" class="form-control" id="theme-name" placeholder="主题名称" required>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" id="theme-description" placeholder="主题描述"></textarea>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" id="theme-keywords" placeholder="关键词（用逗号分隔）">
                        </div>
                        <button type="submit" class="btn btn-primary">✨ 创建主题</button>
                    </form>
                </div>
                
                <div class="card">
                    <h3>📋 现有主题</h3>
                    <button class="btn btn-info" onclick="loadThemes()">🔄 刷新列表</button>
                    <div id="themes-list">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
            
            <!-- 文章生成 -->
            <div id="articles" class="tab-content">
                <div class="card">
                    <h3>📝 生成新文章</h3>
                    <form id="article-form">
                        <div class="form-group">
                            <select class="form-control" id="article-theme" required>
                                <option value="">请选择主题</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label><input type="checkbox" id="include-images" checked> 生成配图</label>
                        </div>
                        <button type="submit" class="btn btn-success">🚀 生成文章</button>
                    </form>
                </div>
                
                <div class="card">
                    <h3>📄 生成的文章</h3>
                    <button class="btn btn-info" onclick="loadArticles()">🔄 刷新列表</button>
                    <div id="articles-list">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
            
            <!-- 系统设置 -->
            <div id="settings" class="tab-content">
                <div class="card">
                    <h3>⚙️ 系统配置</h3>
                    <div id="system-config">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
                
                <div class="card">
                    <h3>💚 系统健康状态</h3>
                    <button class="btn btn-success" onclick="checkHealth()">🔄 检查状态</button>
                    <div id="health-status">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 文章预览模态框 -->
    <div id="articlePreviewModal" class="article-preview-modal">
        <div class="article-preview-content">
            <div class="article-preview-header">
                <h3 class="article-preview-title" id="previewTitle">文章预览</h3>
                <div class="article-preview-controls">
                    <button class="format-toggle" id="formatToggle" onclick="togglePreviewFormat()">📱 微信格式</button>
                    <button class="close-btn" onclick="closeArticlePreview()">×</button>
                </div>
            </div>
            <div class="article-preview-body">
                <div class="article-meta" id="articleMeta">
                    <div class="loading">加载中...</div>
                </div>
                <div class="article-content" id="articleContent">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 标签页切换
        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.nav-item').forEach(tab => tab.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
            
            if(tabName === 'dashboard') loadDashboard();
            if(tabName === 'themes') { loadThemes(); loadThemeOptions(); }
            if(tabName === 'articles') { loadArticles(); loadThemeOptions(); }
            if(tabName === 'settings') { loadSystemConfig(); checkHealth(); }
        }
        
        // API请求封装
        async function apiRequest(url, options = {}) {
            try {
                // 为不同类型的请求设置不同的超时时间
                let timeout = 30000; // 默认30秒
                if (url.includes('/generate') || url.includes('/articles') && options.method === 'POST') {
                    timeout = 300000; // 文章生成请求设为5分钟
                }
                
                // 创建超时控制
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), timeout);
                
                const response = await fetch(url, {
                    headers: { 'Content-Type': 'application/json', ...options.headers },
                    signal: controller.signal,
                    ...options
                });
                
                // 清除超时定时器
                clearTimeout(timeoutId);
                
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                return await response.json();
            } catch (error) {
                if (error.name === 'AbortError') {
                    showAlert('error', '请求超时，请稍后重试');
                } else {
                    showAlert('error', `请求失败: ${error.message}`);
                }
                throw error;
            }
        }
        
        // 显示提示信息
        function showAlert(type, message) {
            const alertClass = type === 'error' ? 'alert-error' : 'alert-success';
            const activeTab = document.querySelector('.tab-content.active');
            const existingAlert = activeTab.querySelector('.alert');
            if (existingAlert) existingAlert.remove();
            
            activeTab.insertAdjacentHTML('afterbegin', `<div class="alert ${alertClass}">${message}</div>`);
            setTimeout(() => {
                const alert = activeTab.querySelector('.alert');
                if (alert) alert.remove();
            }, 5000);
        }
        
        // 显示进度提示
        function showProgressAlert(message, progress) {
            const activeTab = document.querySelector('.tab-content.active');
            const existingAlert = activeTab.querySelector('.alert');
            if (existingAlert) existingAlert.remove();
            
            const progressHtml = `
                <div class="alert alert-info progress-alert">
                    <div class="progress-text">${message}</div>
                    <div class="progress-bar-container">
                        <div class="progress-bar" style="width: ${progress}%"></div>
                    </div>
                    <div class="progress-percentage">${progress}%</div>
                </div>
            `;
            
            activeTab.insertAdjacentHTML('afterbegin', progressHtml);
        }
        
        // 加载仪表板
        async function loadDashboard() {
            try {
                const [themes, articles] = await Promise.all([
                    apiRequest('/api/themes'),
                    apiRequest('/api/articles')
                ]);
                document.getElementById('theme-count').textContent = themes.total || 0;
                document.getElementById('article-count').textContent = articles.total || 0;
            } catch (error) {
                console.error('加载仪表板失败:', error);
            }
        }
        
        // 加载主题列表
        async function loadThemes() {
            const listElement = document.getElementById('themes-list');
            listElement.innerHTML = '<div class="loading">加载中...</div>';
            
            try {
                const data = await apiRequest('/api/themes');
                if (data.items && data.items.length > 0) {
                    listElement.innerHTML = data.items.map(theme => `
                        <div class="card">
                            <h4>${theme.name}</h4>
                            <p>${theme.description || '暂无描述'}</p>
                            <p><strong>关键词:</strong> ${theme.keywords ? theme.keywords.join(', ') : '无'}</p>
                            <button class="btn btn-success" onclick="generateArticle('${theme.id}')">📝 生成文章</button>
                        </div>
                    `).join('');
                } else {
                    listElement.innerHTML = '<p>暂无主题，请先创建一个主题。</p>';
                }
            } catch (error) {
                listElement.innerHTML = '<p>加载失败，请稍后重试。</p>';
            }
        }
        
        // 加载主题选项
        async function loadThemeOptions() {
            try {
                const data = await apiRequest('/api/themes');
                const select = document.getElementById('article-theme');
                select.innerHTML = '<option value="">请选择主题</option>';
                if (data.items) {
                    data.items.forEach(theme => {
                        select.innerHTML += `<option value="${theme.id}">${theme.name}</option>`;
                    });
                }
            } catch (error) {
                console.error('加载主题选项失败:', error);
            }
        }
        
        // 加载文章列表
        async function loadArticles() {
            const listElement = document.getElementById('articles-list');
            listElement.innerHTML = '<div class="loading">加载中...</div>';
            
            try {
                const data = await apiRequest('/api/articles');
                if (data.items && data.items.length > 0) {
                    listElement.innerHTML = data.items.map(article => `
                        <div class="card">
                            <h4>${article.title}</h4>
                            <p>${article.summary || '暂无摘要'}</p>
                            <p><strong>状态:</strong> ${article.status} | <strong>时间:</strong> ${new Date(article.generated_at).toLocaleString()}</p>
                            <button class="btn btn-info" onclick="viewArticle('${article.id}')">👁️ 查看</button>
                            <button class="btn btn-success" onclick="publishArticle('${article.id}')">📤 发布</button>
                            <button class="btn btn-error" onclick="deleteArticle('${article.id}', '${article.title}')">🗑️ 删除</button>
                        </div>
                    `).join('');
                } else {
                    listElement.innerHTML = '<p>暂无文章，请先生成一些文章。</p>';
                }
            } catch (error) {
                listElement.innerHTML = '<p>加载失败，请稍后重试。</p>';
            }
        }
        
        // 加载系统配置
        async function loadSystemConfig() {
            const configElement = document.getElementById('system-config');
            configElement.innerHTML = '<div class="loading">加载中...</div>';
            
            try {
                const data = await apiRequest('/api/config/info');
                configElement.innerHTML = `
                    <p><strong>应用端口:</strong> ${data.app_port}</p>
                    <p><strong>运行环境:</strong> ${data.environment}</p>
                    <p><strong>数据库:</strong> ${data.database_host}</p>
                    <p><strong>微信AppID:</strong> ${data.wechat_app_id}</p>
                `;
            } catch (error) {
                configElement.innerHTML = '<p>加载失败</p>';
            }
        }
        
        // 检查健康状态
        async function checkHealth() {
            const healthElement = document.getElementById('health-status');
            healthElement.innerHTML = '<div class="loading">检查中...</div>';
            
            try {
                const data = await apiRequest('/health');
                const services = data.services || {};
                healthElement.innerHTML = `
                    <p><strong>系统状态:</strong> ${data.status}</p>
                    <p><strong>数据库:</strong> ${services.database === 'connected' ? '✅ 正常' : '❌ 异常'}</p>
                    <p><strong>微信API:</strong> ${services.wechat_api === 'available' ? '✅ 正常' : '❌ 异常'}</p>
                    <p><strong>DeepSeek:</strong> ${services.deepseek_api === 'available' ? '✅ 正常' : '❌ 异常'}</p>
                    <p><strong>通义万相:</strong> ${services.tongyi_api === 'available' ? '✅ 正常' : '❌ 异常'}</p>
                `;
            } catch (error) {
                healthElement.innerHTML = '<p>健康检查失败</p>';
            }
        }
        
        // 创建主题
        document.getElementById('theme-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const formData = {
                name: document.getElementById('theme-name').value,
                description: document.getElementById('theme-description').value,
                keywords: document.getElementById('theme-keywords').value.split(',').map(k => k.trim()).filter(k => k),
                style: 'professional',
                target_audience: 'general',
                content_length: 1500,
                is_active: true
            };
            
            try {
                await apiRequest('/api/themes', { method: 'POST', body: JSON.stringify(formData) });
                showAlert('success', '主题创建成功！');
                document.getElementById('theme-form').reset();
                loadThemes();
                loadThemeOptions();
            } catch (error) {
                showAlert('error', '创建失败，请检查输入信息。');
            }
        });
        
        // 生成文章
        document.getElementById('article-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            const themeId = document.getElementById('article-theme').value;
            if (!themeId) {
                showAlert('error', '请选择一个主题。');
                return;
            }
            
            let progressTimer; // 在外层声明变量
            
            try {
                // 显示初始进度
                showProgressAlert('🚀 开始生成文章...', 5);
                
                const startTime = Date.now();
                
                // 创建定时器，使用更智能的进度更新
                let currentProgress = 5;
                const maxAutoProgress = 90; // 提高到90%，给最后阶段留时间
                
                progressTimer = setInterval(() => {
                    if (currentProgress < maxAutoProgress) {
                        // 更缓慢的增长，避免卡住
                        const increment = Math.random() * 1.5 + 0.5; // 每次增加0.5-2.0%
                        currentProgress = Math.min(currentProgress + increment, maxAutoProgress);
                        
                        let message = '⏳ 正在生成内容...';
                        if (currentProgress < 15) {
                            message = '📝 正在分析主题...';
                        } else if (currentProgress < 25) {
                            message = '✍️ 正在生成标题...';
                        } else if (currentProgress < 40) {
                            message = '📋 正在生成摘要...';
                        } else if (currentProgress < 55) {
                            message = '📄 正在生成内容...';
                        } else if (currentProgress < 70) {
                            message = '🎨 正在生成配图...';
                        } else if (currentProgress < 85) {
                            message = '📤 正在上传素材...';
                        } else {
                            message = '🔄 正在完善细节...';
                        }
                        
                        showProgressAlert(message, Math.floor(currentProgress));
                    }
                }, 1500); // 保持1.5秒更新一次
                
                // 发送API请求
                const response = await apiRequest('/api/articles/generate', {
                    method: 'POST',
                    body: JSON.stringify({
                        theme_id: themeId,
                        include_images: document.getElementById('include-images').checked,
                        num_content_images: 3
                    })
                });
                
                // API响应后，继续显示进度直到100%
                if (progressTimer) {
                    clearInterval(progressTimer);
                    progressTimer = null;
                }
                
                // 从90%到100%的进度显示
                let finalProgress = 90;
                const finalProgressTimer = setInterval(() => {
                    if (finalProgress < 100) {
                        finalProgress += 2;
                        showProgressAlert('✅ 正在完成最后步骤...', Math.min(finalProgress, 100));
                    } else {
                        clearInterval(finalProgressTimer);
                    }
                }, 300); // 更快的更新速度
                
                // 等待最终进度完成
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                const endTime = Date.now();
                const duration = ((endTime - startTime) / 1000).toFixed(1);
                
                if (response.success) {
                    setTimeout(() => {
                        showAlert('success', `文章生成成功！耗时 ${duration} 秒`);
                        loadArticles();
                        loadDashboard();
                    }, 500);
                } else {
                    showAlert('error', `生成失败: ${response.message}`);
                }
                
            } catch (error) {
                // 确保清除定时器
                if (progressTimer) {
                    clearInterval(progressTimer);
                    progressTimer = null;
                }
                showAlert('error', '生成失败，请稍后重试。');
                console.error('文章生成错误:', error);
            }
        });
        
        // 发布文章
        async function publishArticle(articleId) {
            try {
                showAlert('success', '正在发布...');
                await apiRequest('/api/publish/draft', {
                    method: 'POST',
                    body: JSON.stringify({ article_id: articleId, show_cover_pic: true })
                });
                showAlert('success', '发布成功！');
                loadArticles();
            } catch (error) {
                showAlert('error', '发布失败。');
            }
        }
        
        // 查看文章（预览模式）
        async function viewArticle(articleId) {
            try {
                // 显示模态框
                document.getElementById('articlePreviewModal').style.display = 'block';
                
                // 重置状态
                document.getElementById('previewTitle').textContent = '文章预览';
                document.getElementById('articleMeta').innerHTML = '<div class="loading">加载中...</div>';
                document.getElementById('articleContent').innerHTML = '<div class="loading">加载中...</div>';
                
                // 获取文章数据
                const article = await apiRequest(`/api/articles/${articleId}`);
                
                // 更新标题
                document.getElementById('previewTitle').textContent = article.title;
                
                // 更新元信息
                const metaHtml = `
                    <p><strong>📝 文章标题：</strong>${article.title}</p>
                    <p><strong>📄 摘要：</strong>${article.summary || '无摘要'}</p>
                    <p><strong>📅 生成时间：</strong>${new Date(article.generated_at).toLocaleString()}</p>
                    <p><strong>📈 状态：</strong>${article.status}</p>
                    <p><strong>🖼️ 封面图片：</strong>${article.cover_image_id ? '已设置' : '未设置'}</p>
                    <p><strong>📎 配图数量：</strong>${article.media_assets ? article.media_assets.length : 0}张</p>
                    <p><strong>📁 内容长度：</strong>${article.content ? article.content.length : 0}字符</p>
                `;
                document.getElementById('articleMeta').innerHTML = metaHtml;
                
                // 存储原始内容和格式化内容
                window.currentArticle = {
                    raw: article.content || '',
                    formatted: formatContentForPreview(article.content || ''),
                    isWechatFormat: true
                };
                
                // 默认显示微信格式
                showWechatFormat();
                
            } catch (error) {
                document.getElementById('articleMeta').innerHTML = '<p class="alert alert-error">加载失败，请稍后重试。</p>';
                document.getElementById('articleContent').innerHTML = '<p class="alert alert-error">加载失败，请稍后重试。</p>';
                console.error('加载文章失败:', error);
            }
        }
        
        // 关闭文章预览
        function closeArticlePreview() {
            document.getElementById('articlePreviewModal').style.display = 'none';
        }
        
        // 切换预览格式
        function togglePreviewFormat() {
            if (!window.currentArticle) return;
            
            if (window.currentArticle.isWechatFormat) {
                showRawFormat();
            } else {
                showWechatFormat();
            }
        }
        
        // 显示微信格式
        function showWechatFormat() {
            if (!window.currentArticle) return;
            
            const contentDiv = document.getElementById('articleContent');
            contentDiv.innerHTML = `<div class="wechat-format">${window.currentArticle.formatted}</div>`;
            
            document.getElementById('formatToggle').innerHTML = '📋 原始内容';
            window.currentArticle.isWechatFormat = true;
        }
        
        // 显示原始格式
        function showRawFormat() {
            if (!window.currentArticle) return;
            
            const contentDiv = document.getElementById('articleContent');
            contentDiv.innerHTML = `<div class="raw-content">${window.currentArticle.raw}</div>`;
            
            document.getElementById('formatToggle').innerHTML = '📱 微信格式';
            window.currentArticle.isWechatFormat = false;
        }
        
        // 格式化内容为预览模式
        function formatContentForPreview(content) {
            if (!content) return '无内容';
            
            // 将微信富文本格式转换为HTML预览格式
            let formatted = content
                // 将双换行转换为段落
                .split('\n\n')
                .map(paragraph => {
                    if (!paragraph.trim()) return '';
                    
                    // 处理图片标签
                    if (paragraph.includes('<img')) {
                        // 提取图片标签并处理
                        const imgMatch = paragraph.match(/<img[^>]*>/);
                        if (imgMatch) {
                            const imgTag = imgMatch[0];
                            // 提取src属性
                            const srcMatch = imgTag.match(/src="([^"]*)"/);
                            if (srcMatch) {
                                const src = srcMatch[1];
                                // 如果是media_id，显示为占位符
                                if (!src.startsWith('http')) {
                                    return `<div class="image-placeholder" style="background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); border: 2px dashed #ccc; padding: 30px; text-align: center; margin: 20px 0; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
                                        <div style="font-size: 48px; margin-bottom: 10px;">🖼️</div>
                                        <p style="margin: 0; color: #666; font-weight: 500;">图片 (Media ID: ${src.substring(0, 20)}...)</p>
                                        <small style="color: #999;">预览模式下显示为占位符</small>
                                    </div>`;
                                } else {
                                    // 如果是URL，直接显示图片
                                    return `<div style="text-align: center; margin: 20px 0;">
                                        <img src="${src}" alt="配图" style="max-width: 100%; height: auto; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); transition: transform 0.3s ease;" onmouseover="this.style.transform='scale(1.02)'" onmouseout="this.style.transform='scale(1)'" />
                                    </div>`;
                                }
                            }
                        }
                        return paragraph; // 如果无法解析，返回原内容
                    }
                    
                    // 处理标题
                    if (paragraph.includes('📜')) {
                        const title = paragraph.replace(/📜\s*/, '').trim();
                        return `<h2 style="color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; margin: 30px 0 20px 0; font-weight: 600;">${title}</h2>`;
                    }
                    if (paragraph.includes('🔹')) {
                        const title = paragraph.replace(/🔹\s*/, '').trim();
                        return `<h3 style="color: #34495e; border-left: 4px solid #e74c3c; padding-left: 15px; margin: 25px 0 15px 0; font-weight: 500;">${title}</h3>`;
                    }
                    if (paragraph.includes('▫️')) {
                        const title = paragraph.replace(/▫️\s*/, '').trim();
                        return `<h4 style="color: #7f8c8d; margin: 20px 0 10px 0; font-weight: 500;">${title}</h4>`;
                    }
                    
                    // 处理引用
                    if (paragraph.includes('💬')) {
                        const quote = paragraph.replace(/💬\s*/, '').trim();
                        return `<blockquote style="border-left: 4px solid #f39c12; background: #fef9e7; padding: 15px 20px; margin: 20px 0; border-radius: 0 8px 8px 0; font-style: italic; color: #8b4513;">
                            <p style="margin: 0;">${quote}</p>
                        </blockquote>`;
                    }
                    
                    // 处理数字列表
                    if (/^\d+\.\s/.test(paragraph)) {
                        const items = paragraph.split(/\d+\.\s/)
                            .map(item => item.trim())
                            .filter(item => item)
                            .map((item, index) => `<li style="margin: 8px 0; line-height: 1.6;">${item}</li>`)
                            .join('');
                        return `<ol style="padding-left: 25px; margin: 15px 0;">${items}</ol>`;
                    }
                    
                    // 处理列表
                    if (paragraph.includes('•')) {
                        const items = paragraph.split('•')
                            .map(item => item.trim())
                            .filter(item => item)
                            .map(item => `<li style="margin: 8px 0; line-height: 1.6; position: relative; padding-left: 10px;">${item}</li>`)
                            .join('');
                        return `<ul style="padding-left: 25px; margin: 15px 0; list-style: none;">
                            ${items.replace(/<li/g, '<li style="position: relative;"><span style="position: absolute; left: -15px; color: #3498db; font-weight: bold;">•</span>')}
                        </ul>`;
                    }
                    
                    // 处理强调文本
                    paragraph = paragraph.replace(/【([^】]+)】/g, '<strong style="color: #e74c3c; font-weight: 600;">$1</strong>');
                    paragraph = paragraph.replace(/「([^」]+)」/g, '<em style="color: #8e44ad; font-style: italic;">$1</em>');
                    
                    // 处理数据标记
                    paragraph = paragraph.replace(/📊\s*([^\n]+)/g, '<mark style="background: linear-gradient(120deg, #a8edea 0%, #fed6e3 100%); padding: 2px 6px; border-radius: 4px; font-weight: 500;">$1</mark>');
                    
                    // 普通段落
                    return `<p style="line-height: 1.8; margin: 15px 0; text-align: justify; color: #2c3e50;">${paragraph}</p>`;
                })
                .filter(p => p)
                .join('\n');
            
            return formatted || '无内容';
        }
        
        // 删除文章
        async function deleteArticle(articleId, articleTitle) {
            // 显示确认对话框
            const confirmed = confirm(`确定要删除文章「${articleTitle}」吗？\n\n此操作不可撤销，如果文章已发布到微信草稿箱，也会同时删除。`);
            
            if (!confirmed) {
                return;
            }
            
            try {
                showAlert('success', '正在删除文章...');
                
                const response = await apiRequest(`/api/articles/${articleId}`, {
                    method: 'DELETE'
                });
                
                if (response.success) {
                    showAlert('success', '文章删除成功！');
                    // 刷新文章列表和仪表板
                    loadArticles();
                    loadDashboard();
                } else {
                    showAlert('error', `删除失败: ${response.message || '未知错误'}`);
                }
                
            } catch (error) {
                console.error('删除文章错误:', error);
                showAlert('error', '删除失败，请稍后重试。');
            }
        }
        
        // 直接生成文章
        async function generateArticle(themeId) {
            // 切换到文章页面
            switchTab('articles');
            
            // 设置主题
            document.getElementById('article-theme').value = themeId;
            
            let progressTimer; // 在外层声明变量
            let finalProgressTimer; // 声明最终进度定时器
            
            // 自动触发生成
            try {
                showProgressAlert('🚀 开始生成文章...', 5);
                
                const startTime = Date.now();
                
                // 使用更智能的进度策略
                let currentProgress = 5;
                const maxAutoProgress = 90; // 提高到90%
                
                progressTimer = setInterval(() => {
                    if (currentProgress < maxAutoProgress) {
                        const increment = Math.random() * 1.5 + 0.5; // 更平滑的增长
                        currentProgress = Math.min(currentProgress + increment, maxAutoProgress);
                        
                        let message = '⏳ 正在生成内容...';
                        if (currentProgress < 15) {
                            message = '📝 正在分析主题...';
                        } else if (currentProgress < 25) {
                            message = '✍️ 正在生成标题...';
                        } else if (currentProgress < 40) {
                            message = '📋 正在生成摘要...';
                        } else if (currentProgress < 55) {
                            message = '📄 正在生成内容...';
                        } else if (currentProgress < 70) {
                            message = '🎨 正在生成配图...';
                        } else if (currentProgress < 85) {
                            message = '📤 正在上传素材...';
                        } else {
                            message = '🔄 正在完善细节...';
                        }
                        
                        showProgressAlert(message, Math.floor(currentProgress));
                    }
                }, 1400); // 稍快的更新频率
                
                const response = await apiRequest('/api/articles/generate', {
                    method: 'POST',
                    body: JSON.stringify({
                        theme_id: themeId,
                        include_images: true,
                        num_content_images: 3
                    })
                });
                
                // API响应后，继续显示进度直到100%
                if (progressTimer) {
                    clearInterval(progressTimer);
                    progressTimer = null;
                }
                
                // 从90%到100%的进度显示
                let finalProgress = 90;
                finalProgressTimer = setInterval(() => {
                    if (finalProgress < 100) {
                        finalProgress += 2;
                        showProgressAlert('✅ 正在完成最后步骤...', Math.min(finalProgress, 100));
                    } else {
                        clearInterval(finalProgressTimer);
                    }
                }, 300); // 更快的更新速度
                
                // 等待最终进度完成
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                const endTime = Date.now();
                const duration = ((endTime - startTime) / 1000).toFixed(1);
                
                if (response.success) {
                    setTimeout(() => {
                        showAlert('success', `文章生成成功！耗时 ${duration} 秒`);
                        loadArticles();
                        loadDashboard();
                    }, 500);
                } else {
                    showAlert('error', `生成失败: ${response.message}`);
                }
                
            } catch (error) {
                // 确保清除所有定时器
                if (progressTimer) {
                    clearInterval(progressTimer);
                    progressTimer = null;
                }
                if (finalProgressTimer) {
                    clearInterval(finalProgressTimer);
                    finalProgressTimer = null;
                }
                showAlert('error', '生成失败，请稍后重试。');
                console.error('文章生成错误:', error);
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadDashboard();
            
            // 添加模态框外部点击关闭功能
            document.getElementById('articlePreviewModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeArticlePreview();
                }
            });
            
            // 添加ESC键关闭功能
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    closeArticlePreview();
                }
            });
        });
    </script>
</body>
</html>